package edu.gmu.server;

import edu.gmu.middleware.RemoteStub;
import edu.gmu.middleware.Message;
import edu.gmu.middleware.Sink;
import edu.gmu.middleware.SinkFactory;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class RmiSkeleton
{
    protected ServerSocket callbackServerSocket = null;
    protected ServerSocket serverSocket = null;
    protected int port = 0;
    protected int id   = 0;
    protected String name = null;
    
    protected volatile boolean stopped = false;
    
    protected List<RemoteStub> clients = new ArrayList<RemoteStub>();
    protected List<RemoteStub> callbackclients = new ArrayList<RemoteStub>();
    
    
    /**
     * Creates a new RmiSkeleton with specified params.
     */
    public RmiSkeleton( int port, int id, String name )
    {
        this.port = port;
        this.id   = id;
        this.name = name;
        
        /*
         * Handles in separate thread
         */
        Runnable requestTask = new Runnable()
        {
            public void run()
            {
                try
                {
                    listenRequests();
                }
                catch( IOException ioe )
                {
                    ioe.printStackTrace();
                    return;
                }
            }
        };
        Thread requestHandler = new Thread( requestTask );
        requestHandler.setName( "RequestHandler" );
        requestHandler.start();
        
        Runnable callbackTask = new Runnable()
        {
            public void run()
            {
                try
                {
                    //System.out.println( "calling listenCallbacks in rmiskeleton" );
                    listenCallbacks();
                }
                catch( IOException ioe )
                {
                    ioe.printStackTrace();
                    return;
                }
            }
        };
        Thread callbackHandler = new Thread( callbackTask );
        callbackHandler.setName( "CallbackHandler" );
        callbackHandler.start();
    }
    
    
    /**
     * Naive attempt to determine if a port is currently open or not (in use).
     * @param port
     * @return true port is unused, false port is currently being used
     */
    public static boolean isPortOpen( int port )
    {
        boolean open = false;
        try
        {
            ServerSocket ss = new ServerSocket(port);
            open = ss.isBound();
            ss.close();
        }
        catch(IOException ioe)
        {
            // ignore
        }
        return open;
    }
    
    int count = 0;
    /**
     * Starts the server listening on specified port - blocks caller's thread
     * until finished.
     * @param int port
     * @throws java.io.IOException
     */
    public void listenRequests( ) throws IOException
    {
        this.serverSocket = new ServerSocket(this.port);
        
        this.stopped = false;
        while( stopped == false )
        {
            // Blocks until client connects
            final Socket clientSocket = this.serverSocket.accept();
            
            Sink sink = SinkFactory.makeTCPSink(clientSocket );
            final RemoteStub stub = new RemoteStub( sink, id, name );
            // This is adding to shared list from this thread - need to protect
            this.clients.add(stub);
            
            //System.out.println("RmiSkeleton - Client connected.");
            /*
             * Handles in separate thread
             */
            Runnable task = new Runnable()
            {
                public void run()
                {
                    try
                    {
                        handleRequests(stub);
                    }
                    catch( IOException ioe )
                    {
                        //ioe.printStackTrace();
                        //System.out.println( "RmiSkeleton - Client disconnected." );
                    }
                    catch( NullPointerException npe )
                    {
                        // Complain - fix the code
                        npe.printStackTrace();
                    }
                    stub.stop();
                    clients.remove(stub);
                }
            };
            Thread clientThread = new Thread( task );
            clientThread.setName( "HandlerThread-"+count );
            clientThread.start();
            count++;
        }
    }
    
    /**
     * Handles a new client connection.
     * @param Socket clientSocket
     */
    public void handleRequests( RemoteStub stub ) throws IOException
    {
        //--------------------------------------------------------------------//
        // Executed in handlerThread
        //--------------------------------------------------------------------//
        System.out.println( "HandleRequests in RmiSkeleton called - did you override?" );
        stub.stop();
        //--------------------------------------------------------------------//
    }
    
    /**
     * Starts the server listening on specified port - blocks caller's thread
     * until finished.
     * @param int port
     * @throws java.io.IOException
     */
    public void listenCallbacks( ) throws IOException
    {
        //System.out.println("TCPCallbackServer - binding to "+ (this.port+1) );
        this.callbackServerSocket = new ServerSocket(this.port+1);
        
        this.stopped = false;
        while( stopped == false )
        {
            
            // Blocks until client connects
            final Socket clientSocket = this.callbackServerSocket.accept();
            
            //System.out.println("TCPCallbackServer - Client connected.");
            
            /*
             * Handles in this thread - it is a short interaction
             */
            handleCallbacks(clientSocket);
        }
    }
    
    /**
     * Handles a new client connection.
     * @param Socket clientSocket
     */
    public void handleCallbacks( Socket clientSocket )
    {
        //--------------------------------------------------------------------//
        // Executed in handlerThread
        //--------------------------------------------------------------------//
        try
        {
            /*
             * Clean up callbacks
             */
            this.cleanupCallbacks();
            
            Sink sink = SinkFactory.makeTCPSink(clientSocket );
            RemoteStub stub = new RemoteStub( sink, id, name );
            
            // This is adding to shared list from this thread - need to protect
            this.callbackclients.add(stub);
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
        //--------------------------------------------------------------------//
    }
    
    /**
     * Sends the specified message to all clients interested in topic.
     * @param topic
     * @param message
     */
    public void issueCallback( int topic, Message message )
    {
        /*
         * Clean up callbacks
         */
        this.cleanupCallbacks();
        //System.out.println( "callbackclient size: " + this.callbackclients.size() );
        for (int i = 0; i < this.callbackclients.size(); i++)
        {
            RemoteStub callbackStub = callbackclients.get(i);
            try
            {
                //System.out.println( "sending to callbackStub in CalendarSkeleton" );
                callbackStub.send(topic, message);
            }
            catch( IOException ioe )
            {
                // Assume if an error - then disconnect, i.e. cleanup
                //System.out.println( "RmiSkeleton - Callback problem, disconnecting." );
                callbackStub.stop();
                callbackclients.remove(i);
                //ioe.printStackTrace();
            }
        }
    }
    
    /**
     * Removes dead socket connections - because we do not listen to
     * the read all the time with a thread (as non-callbacks sinks)
     * we do not know when the socket has been disconnected!
     */
    private void cleanupCallbacks()
    {
        //System.out.println("CleanupCallbacks - size = "+ this.callbackclients.size());
        for (int i = 0; i < this.callbackclients.size(); i++)
        {
            RemoteStub callbackStub = callbackclients.get(i);
            if( callbackStub.isConnected() == false )
            {
                //System.out.println("Removing dead callback conneciton");
                callbackclients.remove(i);
            }
        }
    }
    
    
    /**
     * Stops the server from listening
     * @throws java.io.IOException
     */
    public void stop()
    {
        this.stopped = true;
        // Stop server - so that we accept no more clients
        try
        {
            if( this.serverSocket != null )         this.serverSocket.close();
            if( this.callbackServerSocket != null ) this.callbackServerSocket.close();
        }
        catch(IOException ioe)
        {
            // ignore
        }
        
        // Stop clients
        for (int i = 0; i < this.clients.size(); i++)
        {
            RemoteStub stub = this.clients.get(i);
            stub.stop();
        }
        
        for (int i = 0; i < this.callbackclients.size(); i++)
        {
            RemoteStub stub = this.callbackclients.get(i);
            stub.stop();
        }
        
        this.clients.clear();
        this.callbackclients.clear();
    }
 
    
    /**
     * Solely to be used for debugging.
     * @param inBuffer
     * @param length
     */
    private static void print( ByteBuffer inBuffer, int length )
    {
        byte[] in = inBuffer.array();
        System.out.print( "position="+inBuffer.position() + " limit="+inBuffer.limit() );
        for (int j = 0; j < length; j++)
        {
            String s = Integer.toHexString( in[j]&0xff );
            if( s.length() == 1 ) s = "0"+s;
            System.out.print( " " + s );
        }
        System.out.println( "" );
    }
    
    
    public static void main( String[] args ) throws IOException
    {
        if( args.length != 3 )
        {
            String s = "Usage: TCPEchoServer port serverId serverName";
            System.out.println( s );
            return;
        }
        
        int port    = Integer.parseInt( args[0] );
        int id      = Integer.parseInt( args[1] );
        String name = args[2];
        
        RmiSkeleton server = new RmiSkeleton(port, id, name);
    }
    

}
